#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("智能灯光控制系统");
    server=new QTcpServer(this);

    //暂时禁用下发按钮
    ui->pushButtonSet->setEnabled(false);

    // 启动服务器
    connect(ui->pushButton, SIGNAL(clicked()),
            this, SLOT(openServerSlot()));

    ui->lineEdit->setText("无连接");

}

Widget::~Widget()
{
    // 关闭监听
    if (server->isListening()) // 判断是否正在监听
    {
        server->close();
    }

    delete ui;
}

//开启服务器槽函数
void Widget::openServerSlot()
{
    //获取端口号
    int port=ui->spinBox->value();
    //开启监听
    bool result =server->listen(QHostAddress::Any,port);
    if(!result)
    {
        QMessageBox::information(this, "提示", "服务器开启失败");
        return ;
    }
    else
    {
        QMessageBox::information(this, "提示", "服务器开启成功");
        //建立连接槽函数
        connect(server,SIGNAL(newConnection()),
                this,SLOT(newConnectionSlot()));

        //开启服务器后禁用开启服务器按钮
        ui->pushButton->setEnabled(false);
    }
}

//建立连接槽函数
void Widget::newConnectionSlot()
{
    if(socket!=NULL)
    {
        socket->close();
    }

    //建立连接
    socket=server->nextPendingConnection();

    //关闭连接槽函数
    connect(socket,SIGNAL(disconnected()),
            this,SLOT(disConnectSlot()));

    //收到消息槽函数
    connect(socket,SIGNAL(readyRead()),
            this,SLOT(readMessageSlot()));

    QString ip=socket->peerAddress().toString();

    quint16 port=socket->peerPort();

    ip.prepend("新连接").append(":").append(QString::number(port));

    ui->lineEdit->setText(ip);

    //启用设置按钮
    ui->pushButtonSet->setEnabled(true);

    //设置(发送)槽函数
    connect(ui->pushButtonSet,SIGNAL(clicked()),
            this,SLOT(sendMessageSlot()));
}

//收到槽函数
void Widget::readMessageSlot()
{
    QByteArray data = socket->readAll();
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data, &error);

    if (error.error == QJsonParseError::NoError)
    {
        QJsonObject obj = doc.object();

        // 更新传感器数据
        ui->lcdNumberTem->display(obj["tem"].toDouble());
        ui->lcdNumberHum->display(obj["hum"].toDouble());
        ui->lcdNumberLight->display(obj["light"].toDouble());
        ui->lcdNumberSmoke->display(obj["smoke"].toDouble());

        // 更新报警状态
        ui->labelWarning->setText(obj["warning"].toInt() ? "开启" : "关闭");
    }
}

//发送槽函数
void Widget::sendMessageSlot()
{
    // 动态获取所有阈值参数
    jsonConfig[TEM_THRESHOLD_KEY] = ui->doubleSpinBoxTem->value();
    jsonConfig[HUM_THRESHOLD_KEY] = ui->doubleSpinBoxHum->value();
    jsonConfig[LIGHT_THRESHOLD_KEY] = ui->doubleSpinBoxLight->value();
    jsonConfig[SMOKE_THRESHOLD_KEY] = ui->doubleSpinBoxSmoke->value();


    // 新增：动态获取灯光模式和流水效果模式
    jsonConfig["light_mod"] = ui->comboBoxLight->currentIndex();  // 假设灯光模式控件名为 comboBoxRGB
    jsonConfig["LED_mod"] = ui->comboBoxLED->currentIndex();    // 假设流水效果控件名为 comboBoxLED
    QJsonDocument doc(jsonConfig);
    QByteArray data = doc.toJson();

    socket->write(data);
}

//断开槽函数
void Widget::disConnectSlot()
{
    QMessageBox::information(this, "提示", "客户端断开连接");
    ui->lineEdit->setText("无连接");
    //关闭设置按钮防止误发
    ui->pushButtonSet->setEnabled(false);
}
